package com.java.demo.java;

import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @auther zhangwj
 * @date 2021/3/18 上午10:40
 */
public class GenerateSign {

    public static void main(String[] args) {
        String secret = "59a824f8808711ebb745361637abd682";

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("timestamp", 1616148098000L);
      //  paramsMap.put("module", "token");
        paramsMap.put("module", "table");
       // paramsMap.put("method", "hdy_access_token");
        paramsMap.put("method", "hdy_get_table_info");
        //paramsMap.put("app_key", "hdy59a31507808711eb99a2361637abd682");
        paramsMap.put("token", "hdy380c559c889a11ebae0d0242ac110002");
        paramsMap.put("app_name", "产业Ding");
        paramsMap.put("table_name", "会员信息库");
        System.out.println(getGenerateSign(paramsMap, secret));

    }

    private static final String SIGN = "sign";

    private static String getGenerateSign(Map<String, Object> paramsMap, String secret) {
        if (null != paramsMap && !paramsMap.isEmpty()) {
            paramsMap.remove(SIGN);
            List<String> paramsList = new ArrayList<>(paramsMap.keySet());
            paramsList.sort(Comparator.naturalOrder());
            StringBuilder sb = new StringBuilder();
            paramsList.forEach(key -> {
                sb.append(key).append(paramsMap.get(key));
            });
            return MD5(secret + sb.toString() + secret);
        }
        return null;
    }

    private static String MD5(String sign) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            StringBuilder sb = new StringBuilder();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(sign.getBytes());
            byte[] encryptStr = md5.digest();
            for (int b : encryptStr) {
                int iRet = b;
                if (iRet < 0) {
                    iRet += 256;
                }
                int iD1 = iRet / 16;
                int iD2 = iRet % 16;
                sb.append(hexDigits[iD1]).append(hexDigits[iD2]);
            }
            return sb.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
}

